﻿using JinfuyuanProject.Entity;
using JinfuyuanProject.Entity.Filter;
using JinfuyuanProject.Entity.ViewModels;
using JinfuyuanProject.Repository;

using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Service.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net.Cache;
using System.Text;
using System.Threading.Tasks;

namespace JinfuyuanProject.Service
{
    public class RoleService : IRoleService
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRoleAndPageRepository _roleAndPageRepository;
        private readonly IModulesRepository _modulesRepository;
        private readonly IPagesRepository _pagesRepository;

        public RoleService(IRoleRepository roleRepository, IRoleAndPageRepository roleAndPageRepository,IModulesRepository modulesRepository,IPagesRepository pagesRepository)
        {
            _roleRepository = roleRepository;
            _roleAndPageRepository= roleAndPageRepository;
            _modulesRepository= modulesRepository;
            _pagesRepository= pagesRepository;
            
        }

        #region 基础方法
        public IQueryable<Role> GetList()
        {
            return _roleRepository.GetList();
        }
        public bool Delete(Role role)
        {
            return _roleRepository.Delete(role);
        }
        public Role GetModel(int Id)
        {
            return _roleRepository.GetModel(Id);

        }
        public int Insert(Role role)
        {
            return _roleRepository.Insert(role);

        }
        public bool Update(Role role)
        {
            return _roleRepository.Update(role);
        }
        #endregion

        #region 业务方法
        public Hashtable Query(RoleFilter filter)
        {
            int count;
            IQueryable<Role> roleList = GetList();//两表关联 使用linq  多表复杂SQL 使用QueryBySql
            Hashtable hashtable = new Hashtable();
            hashtable["code"] = 0;
            hashtable["message"] = "success";
            hashtable["data"] = MakeQueryFilter(roleList, filter, out count);
            hashtable["count"] = count;//结束惰性加载

            return hashtable;
        }

        //得到权限设置数据
        public ModulesPagesVM GetModulePages(int roleId)
        {
            // 获取所有模块
            var modules = _modulesRepository.GetList().ToList();
            // 获取角色已分配的页面ID
            var PageIds = _roleAndPageRepository.GetList()
                                  .Where(x => x.RoleId == roleId)
                                  .Select(p => p.PageId)
                                  .ToList();

            // 获取所有页面（一次性查询优化性能）
            var allPages = _pagesRepository.GetList().ToList();
            // 构建页面VM列表
            var pagesVm = new List<PagesVM>();
            foreach (var module in modules)
            {
                var modulePages = allPages.Where(p => p.ModuleId == module.Id);

                foreach (var page in modulePages)
                {
                    pagesVm.Add(new PagesVM
                    {
                        Id = page.Id,
                        ModuleId = page.ModuleId,
                        PageName = page.PageName,
                        PageUrl = page.PageUrl,
                        IsChecked =PageIds.Contains(page.Id)
                    });
                }
            }
            return new ModulesPagesVM
            {
                Modules = modules,
                Pages = pagesVm
            };
        }
        //角色页面更新
        public Hashtable RoleAndPageUpdate(Role role , List<int> PageIds)
        {
            Hashtable ht = new Hashtable();
            _roleRepository.Update(role);
            int roleId = role.Id;
            var models = _roleAndPageRepository.GetList().Where(x => x.RoleId == roleId).ToList();
            foreach (var roleAndPage in models)
            {
                _roleAndPageRepository.Delete(roleAndPage);
            }
            foreach (int pageId in PageIds)
            {
                RoleAndPage roleAndPage = new RoleAndPage
                {
                    RoleId = roleId,
                    PageId = pageId,
                    CreateTime = DateTime.Now,
                    Isdelete = 0
                };
                _roleAndPageRepository.Insert(roleAndPage);
            }
            ht["code"] = 0;
            ht["msg"] = "success";
            return ht;
        }
        //角色页面添加
        public Hashtable RoleAndPageInsert(Role role, List<int> PageIds)
        {
            Hashtable ht = new Hashtable();
            _roleRepository.Insert(role);
            int roleId = role.Id;
            foreach (int pageId in PageIds)
            {
                RoleAndPage roleAndPage = new RoleAndPage
                {
                    RoleId = roleId,
                    PageId = pageId,
                    CreateTime = DateTime.Now,
                    Isdelete = 0
                };
                _roleAndPageRepository.Insert(roleAndPage);
            }
            ht["code"] = 0;
            ht["msg"] = "success";
            return ht;
        }
        #endregion

        #region 公共方法
        public IQueryable<Role> MakeQueryFilter(IQueryable<Role> role, RoleFilter roleFilter, out int count)
        {
            if (!string.IsNullOrEmpty(roleFilter.RoleName))
            {
                role = role.Where(x => x.RoleName.Contains(roleFilter.RoleName));
            }
            if (!string.IsNullOrEmpty(roleFilter.BaseSalary) && decimal.TryParse(roleFilter.BaseSalary, out decimal baseSalaryValue))
            {
                role = role.Where(x => x.BaseSalary.HasValue && x.BaseSalary.Value == baseSalaryValue);
            }

            if (roleFilter.Isdelete != null)
            {
                role = role.Where(x => x.Isdelete == roleFilter.Isdelete);
            }

            //需要过滤后没做分页前的所有数据条数
            count = role.Count();
            //做分页
            if (roleFilter.page != 0 && roleFilter.limit != 0)
                return role.OrderBy(x => x.Id).Skip((roleFilter.page - 1) * roleFilter.limit).Take(roleFilter.limit);
            else
                return role;
        }

        #endregion
    }
}